package org.example.book.state;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.example.book.decorator.OrderServiceDecorator;
import org.example.book.state.pojo.Order;
import org.example.book.util.Constant;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderStateMachineController {

    @Value("service.level")
    private String serverLevel;

    @Autowired
    private OrderServiceDecorator service;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("sendMqTest")
    public String sendMqTest() {
        rabbitTemplate.convertAndSend("normalExchange", "normalRoutingKey", "afsfafsfa");
        return "ok";
    }

    @PostMapping("create")
    public Order createOrder(@RequestBody String productId) {
        return service.createOrder(productId);
    }

    @PostMapping("pay")
    public Order payOrder(@RequestBody String orderId) {
        return service.pay(orderId);
    }

    @PostMapping("send")
    public Order sendOrder(@RequestBody String orderId) {
        return service.send(orderId);
    }

    @PostMapping("receive")
    public Order receiveOrder(@RequestBody String orderId) {
        return service.receive(orderId);
    }

    /**
     * 支付回调接口。
     * 1、验签
     * 2、后续动作
     *
     * @param request
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping("/alipaycallback")
    public String alipayCallback(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> parameterMap = request.getParameterMap();

        for (Iterator<String> iterator = parameterMap.keySet().iterator(); iterator.hasNext(); ) {
            String name = iterator.next();
            String[] values = parameterMap.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, Constant.APP_PUB_KEY, "UTF-8", Constant.SIGN_TYPE);
        if (signVerified) {
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            String trade_no = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            String total_amount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            service.decoratorPay(out_trade_no, Integer.parseInt(serverLevel), Float.parseFloat(total_amount));
            return "支付成功页面跳转，当前订单为：" + out_trade_no;
        } else {
            throw new UnsupportedOperationException("callback verified failed!!");
        }
    }

    @PostMapping("/friendPay")
    public void friendPay(String sourceCustomer, String orderId, String targetCustomer, String payResult, String role) {


    }
}
